﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Vibz.Common
{
    public class Logs : IDisposable
    {
        static string localBuffer = "";

        FileStream ostrm;
        StreamWriter writer;
        string path = "Logs\\clientfailure_" + DateTime.Now.Millisecond.ToString() + ".log";
        public Logs()
        {
            Directory.CreateDirectory("Logs");
            
            ostrm = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read);
            writer = new StreamWriter(ostrm);

            Console.SetOut(writer);
        }
        public void Dispose()
        {
            try
            {
                writer.Flush();

                ostrm.Close();
                ostrm.Dispose();

                writer.Close();
                writer.Dispose();
            }
            catch (Exception exc) { }
        }
        public string Read()
        {
            return localBuffer;
        }
        public void Write(string message)
        {
            writer.WriteLine(message);
            writer.Flush();
            localBuffer += "\r\n" + message;
        }
        public void Write(Exception exc)
        {
            this.Write(exc.Message + "\r\n" + exc.StackTrace);
            foreach (string key in exc.Data.Keys)
            {
                this.Write(key + ":" + exc.Data[key]);
            }
        }
        public static void WriteMessage(string message)
        {
            Console.WriteLine(message);
            localBuffer += "\r\n" + message;
        }
        public static void WriteError(Exception exc)
        {
            try
            {
                Logs.WriteMessage(exc.Message + "\r\n" + exc.StackTrace);
                foreach (string key in exc.Data.Keys)
                {
                    Logs.WriteMessage(key + ":" + exc.Data[key]);
                }
            }
            catch (Exception ex)
            { // Do nothing }
            }
        }
    }
}
